package com.example.cloudcity.servlet;

import com.google.gson.Gson;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/RemoveFromCartServlet")
public class RemoveFromCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuilder jsonString = new StringBuilder();
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jsonString.append(line);
        }

        // 解析 JSON 数据
        Gson gson = new Gson();
        RemoveRequest removeRequest = gson.fromJson(jsonString.toString(), RemoveRequest.class);

        // 从会话中获取购物车
        HttpSession session = request.getSession();
        ArrayList<String> cart = (ArrayList<String>) session.getAttribute("cart");

        boolean removed = false;
        if (cart != null) {
            removed = cart.remove(removeRequest.item); // 删除商品
        }

        response.setContentType("application/json");
        if (removed) {
            session.setAttribute("cart", cart); // 更新会话中的购物车
            response.getWriter().write("{\"success\": true}");
        } else {
            response.getWriter().write("{\"success\": false, \"error\": \"商品未找到\"}");
        }
    }

    private class RemoveRequest {
        String item;
    }
}
